package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.service.FileStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/**
 * @author moningci
 */
@RestController
@Slf4j
@Api(tags = "通用接口")
@RequestMapping("/admin/common")
public class CommonController {

    @Resource
    private FileStorageService fileStorageService;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file);
        if (file == null || file.getSize() == 0) {
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        // 上传图片到minIo
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String url;
        try {
            url = fileStorageService.uploadImgFile("", fileName + suffix, file.getInputStream());
            log.info("上传图片成功，url:{}", url);
            return Result.success(url);
        } catch (IOException e) {
            log.error("上传图片失败");
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

    @PostMapping("/deleteImage")
    @ApiOperation("删除图片")
    public Result deleteImage(String url) {
        log.info("删除图片，{}", url);
        fileStorageService.delete(url);
        return Result.success();
    }
}
